package com.titan.core.utils.file;

import java.io.File;
import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.titan.core.utils.data.AssertUtils;
import com.titan.core.utils.data.FormatUtils;


/**
 * @author 周成功
 * @email 86898837@qq.com
 * @date 2020年02月14日
 */
public class ClassUtils {
    public static Class<?> getClass(Object object) throws ClassNotFoundException {
        Class<?> classname = null;
        if (object.getClass().isAssignableFrom(java.lang.Class.class)) {
            classname = (Class<?>) object;
        } else if(object instanceof java.lang.String) {
            return ClassUtils.loadClass(FormatUtils.toString(object));
        } else {
            classname = object.getClass();
        }
        return classname;
    }    
    
    public static Class loadClass(String className) throws ClassNotFoundException {
        return loadClass(className, null);
    }
    public static Class loadClass(String className, Class callingClass) throws ClassNotFoundException {
        Class clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException ex) {
                try {
                    clazz = ClassUtils.class.getClassLoader().loadClass(className);
                } catch (ClassNotFoundException exc) {
                    if (callingClass != null) {
                        clazz = callingClass.getClassLoader().loadClass(className);
                    } else {
                        throw exc;
                    }
                }
            }
        }
        return clazz;
    }    
    
    // 判断一个类是否存在
    public static boolean isExistClass(String classname) {
        try {
            Class.forName(classname);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    public static boolean isExistFile(String classname) {
        try {
            AssertUtils.assertNotEmpty(classname, ClassUtils.class, "isExistFile", "classname");
            File file = readFileToFile(classname);
            if(file==null) {
                return false;
            }
            return file.exists();
        } catch (Exception e) {
            return false;
        }
    }
    
    public static File readFileToFile(String classname) throws IOException {
        Resource res2 = new ClassPathResource(classname);
        return res2.getFile();
    }
    
    
}
